package queuedemo;

/**
 * @Author 12629
 * @Description：
 */
public class MyQueue {

    static class Node {
        public int val;
        public Node prev;
        public Node next;

        public Node(int val) {
            this.val = val;
        }
    }

    public Node front;//队头
    public Node rear;//队尾

    /**
     * 约定  队尾是链表的尾巴
     * 约定  队头是链表的头
     * @param val 相当于尾插法
     */
    public void offer(int val) {
        Node node = new Node(val);
        if(front == null) {
            front = node;
            rear = node;
        }else {
            rear.next = node;
            node.prev = rear;
            rear = node;
        }
    }

    public int poll() {
        if(front == null) {
            return -1;
        }

        int val = front.val;
        front = front.next;
        //防止 只有一个节点
        if(front != null) {
            front.prev = null;
        }else {
            rear = null;
        }
        return val;
    }

    public int size() {
        Node cur = front;
        int count = 0;
        while (cur != null) {
            count++;
            cur = cur.next;
        }
        return count;
    }

    public int peek() {
        if(front == null) {
            return -1;
        }
        return front.val;
    }
}
